<template>
  <!-- 条件查询 -->
     <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="编号">
      <el-input v-model="formInline.Product_Number" placeholder="请输入编号" clearable />
    </el-form-item>
       <el-form-item label="名称">
      <el-input v-model="formInline.Product_Name" placeholder="请输入名称" clearable />
    </el-form-item>

        <el-form-item label="类别">
      <el-select
        v-model="ruleForm.category_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in deplarment" :label="item.category_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>



    <el-form-item>
      <el-button type="primary" @click="getdata()">查询</el-button>
    </el-form-item>
  </el-form>


   <!-- 页面数据 -->
  <el-button plain @click="AddWarehouse()">
新增
  </el-button>
           <el-button plain @click="handleExport()">
导出
  </el-button>
  
 <el-table :data="tableData" style="width: 100%">
  <el-table-column prop="product_Number" label="产品编号" width="100" />
    <el-table-column prop="product_Name" label="产品名称" width="100"  />
    <el-table-column prop="manufacturer_Code" label="厂家编码" width="100" />
    <el-table-column prop="internal_Code" label="内部编码" width="100" />
        <el-table-column prop="specifications" label="规格" width="100" />
        <el-table-column prop="category_Name" label="类型" width="100" />
        <el-table-column prop="unit_Name" label="存储单位" width="100" />
        <el-table-column prop="lower_limit" label="预警（下）" width="100" />
        <el-table-column prop="upper_limit" label="预警（上）" width="100" />
        <el-table-column prop="packaging_Type" label="包装类型" width="100" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="weight" label="重量" width="100" />
        <el-table-column prop="supplier_Name" label="默认供应商" width="100" />
    
     <el-table-column fixed="right" label="操作" width="250">
      <template #default="scoped">
        <el-button type="primary" @click="UpdateWarehouse(scoped.row)">编辑</el-button>
      <el-button type="danger" @click="del(scoped.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="page.totalCount"
    />

    <!-- 新增弹窗 -->
<el-dialog
    v-model="dialogVisible"
    title="新增"
    width="800"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="产品编号" prop="">
      <el-input v-model="ruleForm.product_Number" disabled/>
    </el-form-item>
    
    <el-form-item label="产品名称" prop="">
      <el-input v-model="ruleForm.product_Name" />
    </el-form-item>
      <el-form-item label="厂家编码" prop="">
      <el-input v-model="ruleForm.manufacturer_Code" />
    </el-form-item>
      <el-form-item label="内部编码" prop="">
      <el-input v-model="ruleForm.internal_Code" />
    </el-form-item>
    <el-form-item label="单位">
      <el-select
        v-model="ruleForm.unit_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in unit" :label="item.unit_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
    <el-form-item label="类别">
      <el-select
        v-model="ruleForm.category_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in deplarment" :label="item.category_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
      <el-form-item label="上限值" prop="">
      <el-input v-model="ruleForm.lower_limit" />
    </el-form-item>
      <el-form-item label="下限值" prop="">
      <el-input v-model="ruleForm.upper_limit" />
    </el-form-item>
      <el-form-item label="规格" prop="">
      <el-input v-model="ruleForm.specifications" />
    </el-form-item>
    <el-form-item label="价格" prop="">
      <el-input v-model="ruleForm.price" />
    </el-form-item>
      <el-form-item label="重量" prop="">
      <el-input v-model="ruleForm.weight" />
    </el-form-item>
         <el-form-item label="包装类型" prop="">
      <el-input v-model="ruleForm.packaging_Type" />
    </el-form-item>
   <el-form-item label="默认仓库">
      <el-select
        v-model="ruleForm.warehouse_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Ware" :label="item.warehouse_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认库位">
      <el-select
        v-model="ruleForm.storage_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Srtorage" :label="item.storage_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认供应商">
      <el-select
        v-model="ruleForm.supplier_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Supplier" :label="item.supplier_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认客户">
      <el-select
        v-model="ruleForm.customer_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Customer" :label="item.customer_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>

    <el-form-item label="描述" prop="">
 
 <el-input v-model="ruleForm.notes" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>

  <!-- 编辑弹窗 -->
<el-dialog
    v-model="updialogVisible"
    title="编辑"
    width="500"
  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
     <el-form-item label="产品编号" prop="">
      <el-input v-model="ruleForm.product_Number" disabled/>
    </el-form-item>
    
    <el-form-item label="产品名称" prop="">
      <el-input v-model="ruleForm.product_Name" />
    </el-form-item>
      <el-form-item label="厂家编码" prop="">
      <el-input v-model="ruleForm.manufacturer_Code" />
    </el-form-item>
      <el-form-item label="内部编码" prop="">
      <el-input v-model="ruleForm.internal_Code" />
    </el-form-item>
    <el-form-item label="单位">
      <el-select
        v-model="ruleForm.unit_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in unit" :label="item.unit_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
    <el-form-item label="类别">
      <el-select
        v-model="ruleForm.category_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in deplarment" :label="item.category_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
      <el-form-item label="上限值" prop="">
      <el-input v-model="ruleForm.lower_limit" />
    </el-form-item>
      <el-form-item label="下限值" prop="">
      <el-input v-model="ruleForm.upper_limit" />
    </el-form-item>
      <el-form-item label="规格" prop="">
      <el-input v-model="ruleForm.specifications" />
    </el-form-item>
    <el-form-item label="价格" prop="">
      <el-input v-model="ruleForm.price" />
    </el-form-item>
      <el-form-item label="重量" prop="">
      <el-input v-model="ruleForm.weight" />
    </el-form-item>
   <el-form-item label="默认仓库">
      <el-select
        v-model="ruleForm.warehouse_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Ware" :label="item.warehouse_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认库位">
      <el-select
        v-model="ruleForm.storage_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Srtorage" :label="item.storage_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认供应商">
      <el-select
        v-model="ruleForm.supplier_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Supplier" :label="item.supplier_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
       <el-form-item label="默认客户">
      <el-select
        v-model="ruleForm.customer_ID"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="item in Customer" :label="item.customer_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>

    <el-form-item label="描述" prop="">
 
 <el-input v-model="ruleForm.notes" />
    </el-form-item>
 
 
    <el-form-item>
      <el-button type="primary" @click="updatesubmitForm(ruleFormRef)">
        提交
      </el-button>
    </el-form-item>
  </el-form>

  </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive,onMounted, ref, watch } from 'vue'
import { BasicsRed } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { BasicsWrite } from '@/http/axiosHelper'
import { statementRed } from '@/http/axiosHelper'
const router=useRouter();
const dialogVisible = ref(false)
const updialogVisible = ref(false)

const AddWarehouse=()=>
{
   dialogVisible.value=true;
   ruleForm.product_Number= generateDateBasedNumber(),
  ruleForm.product_Name= "",
  ruleForm.manufacturer_Code= "",
  ruleForm.specifications=""
  ruleForm.category_ID=null
  ruleForm.storage_Unit=""
  ruleForm.lower_limit=""
  ruleForm.upper_limit=""
  ruleForm.packaging_Type=""
  ruleForm.price=""
  ruleForm.weight=""
  ruleForm.supplier_ID=null
  ruleForm.warehouse_ID=null
  ruleForm.storage_ID=null
  ruleForm.unit_ID=null
  ruleForm.customer_ID=null
  ruleForm.notes=""
}

const UpdateWarehouse=(row:any)=>
{

 Object.assign(ruleForm,row);
updialogVisible.value=true
}
const updatesubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
   BasicsWrite.post("/api/Product/UpdateProductHandle",ruleForm).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);

       
     

  updialogVisible.value=false;
     getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}


// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};

import {  type FormInstance, type FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:0,
"product_Number": generateDateBasedNumber(),
  "product_Name": "",
  "manufacturer_Code": "",
  "internal_Code": "",
  "specifications": "",
  "category_ID": null,
  "storage_Unit": "个",
  "lower_limit": "",
  "upper_limit": "",
  "packaging_Type": "",
  "price": "",
  "weight": "",
  "supplier_ID": null,
  "warehouse_ID": null,
  "storage_ID": null,
  "unit_ID": null,
  "customer_ID": null,
  "notes": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  region: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  count: [
    {
      required: true,
      message: 'Please select Activity count',
      trigger: 'change',
    },
  ],
  date1: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  date2: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  location: [
    {
      required: true,
      message: 'Please select a location',
      trigger: 'change',
    },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  resource: [
    {
      required: true,
      message: 'Please select activity resource',
      trigger: 'change',
    },
  ],
  desc: [
    { required: true, message: 'Please input activity form', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
   BasicsWrite.post("/api/Product/CreateProductHandle",ruleForm).then(res=>
    {
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);

       
     ruleForm.product_Number= generateDateBasedNumber(),
  ruleForm.product_Name= "",
  ruleForm.manufacturer_Code= "",
  ruleForm.specifications="",
  ruleForm.category_ID=null,
  ruleForm.storage_Unit="",
  ruleForm.lower_limit="",
  ruleForm.upper_limit="",
  ruleForm.packaging_Type="",
  ruleForm.price="",
  ruleForm.weight="",
  ruleForm.supplier_ID=null,
  ruleForm.warehouse_ID=null,
  ruleForm.storage_ID=null,
  ruleForm.unit_ID=null,
  ruleForm.customer_ID=null,
  ruleForm.notes=""
 



  dialogVisible.value=false;
getdata()
    }
    else
    {
            ElMessage.success(res.data.msg);
    }
    }
   )
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}



const formInline = reactive({

  Product_Number: '',
  Product_Name: '',
Category_ID:null
})
const page=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0

})
watch(page,()=>
{
  getdata();
})
onMounted(()=>
{
    delparmentdata();
    getdata();
    unitdata();
    waredata();
    storagedata();
    Supplierdata();
    Customerdata();

})


const del=(id:any)=>
{

ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     BasicsWrite.put("/api/Product/DelProductHandle",{id:id}).then(res=>
{
   if(res.data.code==200)
   {
    ElMessage.success("删除成功");
    getdata();
   }
   else
   {
    ElMessage.success("删除失败");
   }
}
)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })




}
const page2=reactive({
    PageIndex:1,
    PageSize:100,
    totalCount:0

})
//产品类别下拉框
const deplarment=ref()
const delparmentdata=()=>
{
    BasicsRed.get("/api/ProductCategory/GetProductCategoryHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            deplarment.value=res.data.data
        }
    )
}
//产品单位下拉框
const unit=ref()
const unitdata=()=>
{
    BasicsRed.get("/api/Unit/GetUnitHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            unit.value=res.data.data
        }
    )
}
//仓库下拉框
const Ware=ref()
const waredata=()=>
{
    BasicsRed.get("/api/Warehouse/GetWarehouseHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            Ware.value=res.data.data
        }
    )
}
//库位下拉框
const Srtorage=ref()
const storagedata=()=>
{
    BasicsRed.get("/api/Storage/GetStorageHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            Srtorage.value=res.data.data
        }
    )
}
//供应商下拉框
const Supplier=ref()
const Supplierdata=()=>
{
    BasicsRed.get("/api/Supplier/GetSupplierHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            Supplier.value=res.data.data
        }
    )
}
//客户下拉框
const Customer=ref()
const Customerdata=()=>
{
    BasicsRed.get("/api/Customer/GetCustomerHandle",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            Customer.value=res.data.data
        }
    )
}

const tableData=ref([]);

const getdata=()=>
{
    BasicsRed.get("/api/Product/GetProductHandle",{params:{
      PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Product_Number:formInline.Product_Number,
      Product_Name:formInline.Product_Name,
      Category_ID:formInline.Category_ID
     
    
    
    }}).then(res=>
        {
tableData.value=res.data.data
page.totalCount=res.data.totalCount
        }
    )
}

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BasicsRed({
            url: '/api/Product/GetProductExport', // 后端接口地址
            method: 'GET',
            params: {
                   PageIndex:page.PageIndex,
                    PageSize:page.PageSize,
                    Product_Number:formInline.Product_Number,
                    Product_Name:formInline.Product_Name,
                    Category_ID:formInline.Category_ID
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}


// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '产品管理.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '产品管理.xlsx';
}



const onSubmit = () => {
  console.log('submit!')
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 120px;
}

.demo-form-inline .el-select {
  --el-select-width: 120px;
}

/* 下拉框宽度样式 */
.warehouse-select {
  min-width: 200px;
  width: 100%;
}

.warehouse-select :deep(.el-input__wrapper) {
  min-width: 200px;
}

.warehouse-select :deep(.el-input__inner) {
  min-width: 200px;
}
</style>